package org.jrpc.proxy;

import org.jrpc.base.IClient;
import org.jrpc.base.IClientManage;
import org.jrpc.base.ResultResponse;
import org.jrpc.common.baen.RpcRequest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * Created by chenyuncong on 2019/4/10.
 */
public class MyProxy implements InvocationHandler {

    private Class<?> interfaceClass;

//    private IClient iClient;

    private IClientManage iClientManage;

    private String serviceName;

    //远程接口描述集合

    public Object bind(Class<?> cls, IClientManage iClientManage,String serviceName) {
        this.interfaceClass = cls;
        this.iClientManage = iClientManage;
        this.serviceName=serviceName;
        return Proxy.newProxyInstance(cls.getClassLoader(), new Class[]{interfaceClass}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest request = new RpcRequest();
        request.setRequestId(UUID.randomUUID().toString());
        request.setInterfaceName(method.getDeclaringClass().getName());
        request.setServiceVersion("");
        request.setMethodName(method.getName());
        request.setParameterTypes(method.getParameterTypes());
        request.setParameters(args);
        // 获取 RPC 服务地址
                       /*
                        if (serviceDiscovery != null) {
                            String serviceName = interfaceClass.getName();
                            if (StringUtil.isNotEmpty(serviceVersion)) {
                                serviceName += "-" + serviceVersion;
                            }
                            serviceAddress = serviceDiscovery.discover(serviceName);
                            LOGGER.debug("discover service: {} => {}", serviceName, serviceAddress);
                        }
                        if (StringUtil.isEmpty(serviceAddress)) {
                            throw new RuntimeException("server address is empty");
                        }
                        // 从 RPC 服务地址中解析主机名与端口号
                        String[] array = StringUtil.split(serviceAddress, ":");
                        String host = array[0];
                        int port = Integer.parseInt(array[1]);
                        */
        // 创建 RPC 客户端对象并发送 RPC 请求
//                        RpcClient client = new RpcClient(host, port);
        long time = System.currentTimeMillis();
        ResultResponse response = iClientManage.put(serviceName,request);
        if (response == null) {
            throw new RuntimeException("response is null");
        }
        // 返回 RPC 响应结果
        if (response.getRpcResponse().hasException()) {
            throw response.getRpcResponse().getException();
        } else {
            return response.getRpcResponse().getResult();
        }
    }

}